package com.sim.action;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.sim.base.BaseAction;
import com.sim.domain.Society;
import com.sim.domain.SocietyType;
import com.sim.domain.User;
import com.sim.util.QueryHelper;


@Controller
@Scope("prototype")
@SuppressWarnings("serial")
public class SocietyAction extends BaseAction<Society> {
	private Long societyTypeId;
	/**
	 * true 表示升序<br>
	 * false 表示降序
	 */
	private boolean asc = false;
	//主页面
    public String list() throws Exception {
    	//准备信息
    	SocietyType societyType = societyTypeService.getById(societyTypeId);
    	new QueryHelper(Society.class, "s")//
    	    .addOrderProperty(true, "s.currentTime", asc) // 1 表示只按最后更新时间排序 
    	    .addCondition(true, "s.societyType=?",societyType)//传入资助类型对象
    	    .preparePageBean(societyService, pageNum, pageSize);		    
       
    	return "list";
    }
	//展示活动信息
	public String show() throws Exception {
        //准备用户对象
    	Society society = societyService.getById(model.getId());    	
    	ActionContext.getContext().getValueStack().push(society);
    	return "show";
    }
	 // 用户关注活动
    public String watch() throws Exception {
        //准备用户对象
    	Society society = societyService.getById(model.getId());
    	User user = getCurrentUser();
    	List<User> userList=null;
    	if(society.getUsers()!=null){
    	  Set<User> users = society.getUsers();    	
    	   userList = new ArrayList<User>(users);
    	   userList.add(user);
    	}else{
    	    userList = new ArrayList<User>();
        	userList.add(user);	
    	}
    	society.setUsers(new HashSet<User>(userList));
    	societyService.update(society);
    	return "toShow";
    }
    //用户取消关注
    public String unWatch() throws Exception {
        //准备用户对象
    	Society society = societyService.getById(model.getId());
    	User user = getCurrentUser();
    	Set<User> users = society.getUsers();    	
    	List<User> userList = new ArrayList<User>(users);
    	for(int i=0;i<userList.size();i++){
    		if(user.getId().equals(userList.get(i).getId())){
    			userList.remove(i);
    		}
    	}
    	society.setUsers(new HashSet<User>(userList));
    	societyService.update(society);
    	return "toShow";
    }
    //================
	public Long getSocietyTypeId() {
		return societyTypeId;
	}
	public void setSocietyTypeId(Long societyTypeId) {
		this.societyTypeId = societyTypeId;
	}
    
}
